package cn.yuanqiao.archive.Identify.service.impl;

import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.archive.Identify.domain.*;
import cn.yuanqiao.archive.Identify.domain.vo.DestroyCarVo;
import cn.yuanqiao.archive.Identify.mapper.DestroyCarMapper;
import cn.yuanqiao.archive.Identify.mapper.DestroyMapper;
import cn.yuanqiao.archive.Identify.service.DestroyService;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqFolderMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqItemMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.impl.WenjianzhengliServiceImpl;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.enums.BusinessBehavior;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.util.BusinessBehaviorUtil;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.manage.domain.ManageFonds;
import cn.yuanqiao.manage.mapper.ManageFondsMapper;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DestroyServiceImpl implements DestroyService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private DestroyCarMapper destroyCarMapper;
    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;
    @Autowired
    private WenjianzhengliServiceImpl wenjianzhengliService;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private TenantMijiComparisonTableServiceImpl mijiComparisonTableService;
    private String dataBaseId;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @PostConstruct
    public void getDatabaseId() {
        dataBaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
    }

    @Autowired
    private DestroyMapper destroyMapper;
    @Autowired
    private RemoteActivitiService activitiService;
    @Autowired
    private ITenantSysConfigService configService;
    @Autowired
    private ManageFondsMapper fondsMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private ITenantSysDictTypeService dictTypeService;
    @Autowired
    private TenantItemFolderMapper tenantItemFolderMapper;
    @Autowired
    private TenantYqItemMapper itemMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;

    @Override
    public List<Map<String, Object>> getlist(JSONObject json) {
        Long categoryId = json.getLong("categoryId");//门类id
        Long menuId = json.getLong("menuId");//菜单id
        String subTableName = json.getString("subTableName");//层级节点的表名
        JSONArray propertyName = json.getJSONArray("propertyName");//分类节点的属性
        JSONArray propertyValue = json.getJSONArray("propertyValue");//分类节点的值
        //Long fondsId=json.getLong("fondsId");//全宗id
        String fields = " ID,STATE," + json.getString("fields");//需要查询的字段
        JSONArray jsonArray = json.getJSONArray("searchcolumn");//查询条件
        StringBuilder sb = new StringBuilder(" and ");//用于拼接条件
        String orderstr = json.getString("order");//用于排序
        Integer state = json.getInteger("state");
        //Integer state = 8;
        int type = -1;
        /**处理查询条件*/
        if (null == jsonArray) {
            jsonArray = new JSONArray();
        }

        if (FBswitch) {
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            sb.append(" MJ in ('" + getdamjbyrymj.stream().map(m -> m.getDaMj()).collect(Collectors.joining("','")) + "') and ");
        }

        if (jsonArray.size() > 0) {
            wenjianzhengliService.concatQueryCondition(jsonArray, sb);
        }
        /**处理表名*/
        String tablename = "";
        TenantCategory category = new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        //判断门类类型
        String categoryType="";
        if (tenantCategory.getType() == 0) {//件
            categoryType="F";
        }
        if (null != subTableName && !"".equals(subTableName)) {//有层级信息
            tablename = subTableName;
            String tablenametype = subTableName.substring(subTableName.length() - 3, subTableName.length() - 2);
            if ("F".equalsIgnoreCase(tablenametype)) {//档案层
                type = 0;
            } else if ("V".equalsIgnoreCase(tablenametype)) {//案卷层
                type = 1;
            } else if ("X".equalsIgnoreCase(tablenametype)) {//项目层
                type = 1;
                tablename = subTableName.substring(0, subTableName.length() - 3) + "V" + subTableName.substring(subTableName.length() - 2, subTableName.length());
            } else if ("E".equalsIgnoreCase(tablenametype)) {//电子文件层
                type = 2;
            }
        } else {
           // TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            if (tenantCategory.getType() == 0) {//件
                tablename = tenantCategory.getFileTableName();
            } else if (tenantCategory.getType() == 1) {//卷
                tablename = tenantCategory.getFolderTableName();
            } else if (tenantCategory.getType() == 2) {//电子文件
                tablename = tenantCategory.getEfileTableName();
            } else if (tenantCategory.getType() == 3) {//项目
                tablename = tenantCategory.getFolderTableName();
            }
            type = tenantCategory.getType();
            if (3 == type) {
                type = 1;
            }
        }
        /**处理分类值*/
        if (propertyName.size() > 0) {
            for (int i = 0; i < propertyName.size(); i++) {
                sb.append(" " + propertyName.get(i) + " = " + "'" + propertyValue.get(i) + "' and ");
            }
        }
        String tiaojian = sb.toString();
        /**处理拼接条件时的sql*/
        if (tiaojian.endsWith("and ")) {
            tiaojian = tiaojian.substring(0, tiaojian.length() - 4);
        } else if (tiaojian.endsWith("and")) {
            tiaojian = tiaojian.substring(0, tiaojian.length() - 3);
        }
        /**处理排序*/
        if (null != orderstr && !"".equals(orderstr)) {
            orderstr = " order by " + orderstr;
        } else {
            String applyorderstr = tenantMdataListService.getorder(categoryId, menuId, type);
            if (null != applyorderstr && !"".equals(applyorderstr)) {
                orderstr = " order by " + applyorderstr;
            }
        }
        PageUtils.startPage();
        /** 拼接条件(bgqx到期/未鉴定过/已在流程中) */
        /*bgqx到期*/
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String nowdate = sdf.format(date);
        String bgqxgqsql = "";
        //2024-10-14 按年度判断过期,目前只修改了瀚高数据库 赵常飞
        if (dataBaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())) {
            bgqxgqsql = "select id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,rq,jdsj," +
                    "to_char(TO_DATE((case when jdsj is null then (case  when RQ IS NOT NULL then rq else '19000101'  end) " +
                    "else jdsj end ), case when locate('-',(CASE WHEN jdsj IS NULL THEN (CASE WHEN rq IS NOT NULL THEN rq ELSE '19000101' END ) ELSE jdsj END))!=0 then 'YYYY-MM-DD' else 'YYYYMMDD' END),'YYYYMMDD') as formatrq,(to_char(TO_DATE((case when jdsj is null then (case " +
                    " when RQ IS NOT NULL then rq else '19000101'  end) else jdsj end )," +
                    " case when locate('-',(CASE WHEN jdsj IS NULL THEN (CASE WHEN rq IS NOT NULL THEN rq ELSE '19000101' END ) ELSE jdsj END))!=0 then 'YYYY-MM-DD' else 'YYYYMMDD' END)+replace(bgqx, 'D', '')*365,'YYYYMMDD')) as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ') where gqsj<='" + (nowdate.length()>4?nowdate:nowdate+"0101") + "'";
        } else if (dataBaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || dataBaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())) {
//            bgqxgqsql = "select id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,nd,jdsj," +
//                    "to_char(TO_DATE((case when jdsj is null then (case  when nd IS NOT NULL then nd else '1900'  end) " +
//                    "else jdsj end ), 'YYYY' ),'YYYY') as formatrq,(to_char(TO_DATE((case when jdsj is null then (case " +
//                    " when nd IS NOT NULL then nd else '1900'  end) else jdsj end )," +
//                    " 'YYYY')+cast(replace(bgqx,'D','')+1 as integer)*365,'YYYY')) as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ' ) where gqsj<='" + nowdate + "'";
        } else  if (dataBaseId.equalsIgnoreCase(DbIdEnum.DM.getCode()) ) {
            bgqxgqsql = "select id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,rq,jdsj,DATE_FORMAT((case when jdsj is null then (case  when (isdate(rq))=1 then rq else '19000101'  end) else jdsj end ), 'YYYYMMDD') as formatrq,(DATE_FORMAT((case when jdsj is null then (case  when (isdate(rq))=1 then rq else '19000101'  end) else jdsj end ), 'YYYYMMDD')+replace(bgqx, 'D', '')*10000)as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ')where gqsj<='" + nowdate + "'";
        }else{

            bgqxgqsql = "select /*+ENABLE_IN_VALUE_LIST_OPT(0)*/ id from(select id,replace(bgqx, 'D', '') as bgqxnum,bgqx,rq,jdsj,DATE_FORMAT((case when jdsj is null then (case  when (isdate(rq))=1 then rq else '19000101'  end) else jdsj end ), 'YYYYMMDD') as formatrq,(DATE_FORMAT((case when jdsj is null then (case  when (isdate(rq))=1 then rq else '19000101'  end) else jdsj end ), 'YYYYMMDD')+replace(bgqx, 'D', '')*10000)as gqsj from " + tablename + " where bgqx !='Y' and bgqx !='CQ' and bgqx != 'DQ')where gqsj<='" + nowdate + "'";
        }
        /*未鉴定过*/
        //不在保管期限和销毁流程中
        TenantYqbgqxjdJobDa yqbgqxjdJobDa = new TenantYqbgqxjdJobDa();
        TenantYqbgqxjdJob yqbgqxjdJob = new TenantYqbgqxjdJob();
        TenantYqxhjdJobDa yqxhjdJobDa = new TenantYqxhjdJobDa();
        TenantYqxhjdJob yqxhjdJob = new TenantYqxhjdJob();
        TenantYqbgqxjdFolderDa tenantYqbgqxjdFolderDa = new TenantYqbgqxjdFolderDa();
        String lczsql="";
        //案件层逻辑不对
        if(type==0&&"".equals(categoryType)){ //查看件层且门类不是组件类型时
            lczsql = " (select daid from "+tenantYqbgqxjdFolderDa.getTableName()+" where renwuid in(select id from " + yqbgqxjdJob.getTableName() + " where is_del=0 and jiandingstate=8)" +
                    " and  shending_chuzhifangshi= '2' )";//未撤销且鉴定未完成
        }else{
            lczsql = " (select daid from " + yqbgqxjdJobDa.getTableName() + " where renwuid in(select id from " + yqbgqxjdJob.getTableName() + " where is_del=0 and jiandingstate=8)" +
                    " and  shending_chuzhifangshi= '2' )";//未撤销且鉴定未完成
        }
        /**查询列表并返回*/
        return destroyMapper.getlistnew(fields, tablename, bgqxgqsql, lczsql, tiaojian, orderstr, "id",state);
    }

    @Override
    @Transactional
    public void destroyDel(String ids,Long categoryId) {
        //destroyMapper.delDispose(SecurityUtils.getTenantCode(),ids);


        //DestroyCar select = new  DestroyCar();
        //select.setDestroyId(destroyId);
        //List<DestroyCar> list = destroyCarMapper.findAll(select);
        String [] idd = ids.split(",");
        for(String da:idd){
            Long id = Long.valueOf(da);
            //2.根据分表查询门类
            TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
            if(category.getType() == 3){
                /*List<String> itemId = tenantItemFolderMapper.selectItemIdByFolderId(String.valueOf(id),new TenantItemFolder().getTableName());
                if(itemId!=null && itemId.size()>0){
                    itemMapper.delYqItem(itemId.get(0),new TenantYqItem().getTableName());
                    destroyMapper.delArchive(Long.valueOf(itemId.get(0)),category.getItemTableName());
                }*/
            }

            if(category.getType() == 1 || category.getType() == 3){
                //修改卷
                Long folderId = id;
                folderMapper.delYqFolder(folderId,new TenantYqFolder().getTableName());
                destroyMapper.delArchive(folderId,category.getFolderTableName());

                //修改件
                Long [] folderIds = new Long[]{folderId};
                Long [] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds,category.getFileTableName(),new TenantYqdaFolder().getTableName());

                for(Long daId:daIds){
                    yqdaMapper.delYqda(daId,new TenantYqda().getTableName());
                    destroyMapper.delArchive(daId,category.getFileTableName());
                }
            } else if(category.getType() == 0){
                //处理组件
                Long daId = id;
                yqdaMapper.delYqda(daId,new TenantYqda().getTableName());
                destroyMapper.delArchive(daId,category.getFileTableName());
            }
        }
    }

    @Override
    public void addDestroy(Destroy destroy) {
        Long id = SnowflakeIdGenerator.generateId();
        destroy.setDestroyId(id);
        destroy.setTenantCode(SecurityUtils.getTenantCode());
        destroy.setCreateTime(new Date());
        destroy.setStatus(0);
        destroyMapper.insert(destroy);

        //绑定销毁单
        DestroyCar destroyCar = new DestroyCar();
        destroyCar.setDestroyId(id);
        destroyCar.setTenantCode(SecurityUtils.getTenantCode());
        destroyCar.setUserId(SecurityUtils.getUserId());
        destroyCarMapper.bindDestroy(destroyCar);
        //启发流程
        logger.info(destroyCar.toString());
        Map<String,Object> variables = new HashMap();
        variables.put("processVariables",destroy.toProcessMap());

        DestroyCar select = new DestroyCar();
        select.setTenantCode(SecurityUtils.getTenantCode());
        select.setDestroyId(id);
        Long categoryId = destroyCarMapper.getCategoryId(destroyCar);
        List<DestroyCarVo> carVos = new ArrayList<>();
        if(categoryId != null){
            TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
            /*if(category.getType()==3){
                carVos = destroyCarMapper.findDestroyCarVoByItem(SecurityUtils.getTenantCode(),category.getFileTableName(),category.getFolderTableName(),destroyId);
            }else*/ if(category.getType()==1 || category.getType()==3){
                carVos = destroyCarMapper.findDestroyCarVoByFolder(SecurityUtils.getTenantCode(),category.getFileTableName(),category.getFolderTableName(),id);
            }else if(category.getType()==0){
                carVos = destroyCarMapper.findDestroyCarVoByYqda(SecurityUtils.getTenantCode(),category.getFileTableName(),id);
            }
        }
        List<Map> mapList = new ArrayList<>();
        for(DestroyCarVo carVo:carVos){
            mapList.add(carVo.toProcessMap());
        }
        variables.put("archiveData",mapList);

        logger.info(variables.toString());
        R<ActivitiPackage> activitiPackageR = activitiService.startProcessArchiveDestroy(variables);
        String activitiId = activitiPackageR.getData().getProcessInstance().getId();
        logger.info("流程ID="+activitiId);

        //String activitiId = String.valueOf(SnowflakeIdGenerator.generateId());

        Destroy update = new Destroy();
        update.setActivitiId(Long.valueOf(activitiId));
        update.setStatus(1);
        update.setDestroyId(id);
        destroyMapper.update(update);
    }

    @Override
    public List<Destroy> destroyList(Destroy destroy) {
        //PageUtils.startPage();
        destroy.setTenantCode(SecurityUtils.getTenantCode());
        return destroyMapper.findAll(destroy);
    }
    @Override
    public List<Destroy> destroyList1(Destroy destroy) {
        //PageUtils.startPage();
        destroy.setTenantCode(SecurityUtils.getTenantCode());

        return destroyMapper.findAll1(destroy);
    }
    @Override
    @Transactional
    public void endDestroy(Long destroyId) {
        Destroy update = new Destroy();
        update.setStatus(2);
        update.setDestroyId(destroyId);
        destroyMapper.update(update);
        //修改档案状态
        updateDaStat(destroyId,"8");
    }

    @Override
    public void backDestroy(Long destroyId) {
        Destroy update = new Destroy();
        update.setStatus(-1);
        update.setDestroyId(destroyId);
        destroyMapper.update(update);
    }

    @Override
    public void upload(Long destroyId, MultipartFile multipartFile) {
        String qzjPath = configService.selectConfigByKey("YQ_MNT");
        if(StringUtils.isEmpty(qzjPath)){
            throw new ServiceException("缺少系统参数YQ_MNT");
        }
        File file = new File(qzjPath+File.separator+"destroyFile");
        if(!file.exists()){
            file.mkdirs();
        }
        String fileName = multipartFile.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        String filePath = file.getAbsolutePath() +File.separator+ new Date().getTime() + "." + fileType;
        try {
            multipartFile.transferTo(new File(filePath));
        }catch (IOException e){
            logger.error(e.getMessage(),e);
            throw new ServiceException("文件保存失败!"+e.getMessage());
        }
        Destroy update = new Destroy();
        update.setDestroyListPath(filePath);
        update.setDestroyId(destroyId);
        destroyMapper.update(update);
    }

    @Override
    public void clearFilePath(Long destroyId) {
        destroyMapper.clearFilePath(destroyId);
    }

    @Override
    public void insert(DestroyCar destroyCar) {
        DestroyCar car = destroyCarMapper.findByDaId(destroyCar.getDaId());
        if(car==null){
            destroyCar.setDaType(destroyCar.getDaType() == 3 ? 1:destroyCar.getDaType());
            destroyCar.setCreateTime(new Date());
            destroyCar.setCarId(SnowflakeIdGenerator.generateId());
            destroyCar.setTenantCode(SecurityUtils.getTenantCode());
            destroyCar.setUserId(SecurityUtils.getUserId());
            destroyCar.setStatus(0);
            Long categoryId = destroyCarMapper.getCategoryId(destroyCar);
            if(categoryId==null || categoryId.equals(destroyCar.getCategoryId())){
                destroyCarMapper.insert(destroyCar);
            }else {
                throw new ServiceException("销毁申请单已存在其他门类数据，不能添加多个门类！");
            }
        }
    }

    @Override
    public void update(DestroyCar destroyCar) {
        destroyCarMapper.update(destroyCar);
    }
    @Override
    public void update1(Long destroyId) {
        destroyMapper.update1(destroyId);
    }
    @Override
    public List<DestroyCarVo> findDestroyCarVo(Long destroyId) {
        DestroyCar destroyCar = new DestroyCar();
        destroyCar.setTenantCode(SecurityUtils.getTenantCode());
        destroyCar.setUserId(SecurityUtils.getUserId());
        destroyCar.setDestroyId(destroyId);
        Long categoryId = destroyCarMapper.getCategoryId(destroyCar);
        List<DestroyCarVo> carVos = new ArrayList<>();
        if(categoryId != null){
            TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
            /*if(category.getType()==3){
                carVos = destroyCarMapper.findDestroyCarVoByItem(SecurityUtils.getTenantCode(),category.getFileTableName(),category.getFolderTableName(),destroyId);
            }else*/ if(category.getType()==1 || category.getType()==3){
                carVos = destroyCarMapper.findDestroyCarVoByFolder(SecurityUtils.getTenantCode(),category.getFileTableName(),category.getFolderTableName(),destroyId);
            }else if(category.getType()==0){
                carVos = destroyCarMapper.findDestroyCarVoByYqda(SecurityUtils.getTenantCode(),category.getFileTableName(),destroyId);
            }
        }
        return carVos;
    }

    @Override
    @Transactional
    public void deleteByIds(String ids) {
        //ids 是档案ID
        String [] id = ids.split(",");
        for(String idd:id){
            DestroyCar destroyCar = destroyCarMapper.findByDaId(Long.valueOf(idd));
            /*if(destroyCar.getCategoryId() == 3){
                //查询项目ID
                List<String> itemId = tenantItemFolderMapper.selectItemIdByFolderId(idd,new TenantItemFolder().getTableName());
                destroyCarMapper.deleteByDaId(Long.valueOf(itemId.get(0)));
            }else {
                destroyCarMapper.deleteByDaId(Long.valueOf(idd));
            }*/
            destroyCarMapper.deleteByDaId(Long.valueOf(idd));
        }
    }
    @Override
    public String download(Long destroyId){
        String uplodPath = sysConfigService.selectConfigByKey("YQ_YIJIAO");
        if(StringUtils.isEmpty(uplodPath)){
            throw new ServiceException("系统参数错误YQ_YIJIAO未找到配置！");
        }
        File filePath = new File(uplodPath+"model"+File.separator);
        if(!filePath.exists()){
            filePath.mkdirs();
        }

        String outPath = uplodPath+File.separator+"destroy"+File.separator+destroyId+".docx";
        if(!new File(outPath).getParentFile().exists()){
            new File(outPath).getParentFile().mkdirs();
        }
        if(new File(outPath).exists()){
            return outPath;
        }

        DestroyCar destroyCar = new DestroyCar();
        destroyCar.setTenantCode(SecurityUtils.getTenantCode());
        destroyCar.setDestroyId(destroyId);
        Long categoryId = destroyCarMapper.getCategoryId(destroyCar);
        Destroy destroy = destroyMapper.findById(destroyId);
        TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId,new TenantCategory().getTableName());
        List<DestroyCarVo> carVos = null;
        /*if(category.getType()==3){
            carVos = destroyCarMapper.findDestroyCarVoByItem(SecurityUtils.getTenantCode(),category.getFileTableName(),category.getFolderTableName(),destroyId);
        }else*/ if(category.getType()==1 || category.getType()==3){
            carVos = destroyCarMapper.findDestroyCarVoByFolder(SecurityUtils.getTenantCode(),category.getFileTableName(),category.getFolderTableName(),destroyId);
        }else if(category.getType()==0){
            carVos = destroyCarMapper.findDestroyCarVoByYqda(SecurityUtils.getTenantCode(),category.getFileTableName(),destroyId);
        }
        List<String[]> data = new ArrayList<>();
        //String [] title = new String[]{"档号","题名","年度","件数","页数","保管期限","销毁时间"};
        //data.add(title);
        List<TenantSysDictData> dictDataList = dictTypeService.selectDictDataByType("BGQX");

        for(DestroyCarVo carVo:carVos){
            String bgqxVal = "";
            for(TenantSysDictData dictData:dictDataList){
                if(dictData.getDictValue().equals(carVo.getBgqx())){
                    bgqxVal = dictData.getDictLabel();
                }
            }
            String [] dataDoc = new String[]{
                    StringUtils.getStringNull(carVo.getDh()),
                    StringUtils.getStringNull(carVo.getTitle()),
                    StringUtils.getStringNull(carVo.getNd()),
                    StringUtils.getStringNull(carVo.getFileCount()),
                    StringUtils.getStringNull(carVo.getYs()),
                    bgqxVal,
                    //DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,destroy.getDestroyDate()),
                    getName(carVo.getCsczfs()),
                    StringUtils.getStringNull(carVo.getCsczyj()),
                    getName(carVo.getFsczfs()),
                    StringUtils.getStringNull(carVo.getFsczyj()),
                    getName(carVo.getSdczfs())
            };
            data.add(dataDoc);
        }

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("qzh", category.getFondsCode());
        ManageFonds manageFonds = fondsMapper.selectManageFondsByCode(category.getFondsCode(), SecurityUtils.getTenantCode());
        dataMap.put("qzhName",manageFonds.getFondsName());
        dataMap.put("categoryName", category.getName());

        OutputStream outputStream = null;
        InputStream templateInputStream = null;
        XWPFDocument document = null;
        try {
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            File outputFile = new File(uplodPath+"model"+File.separator+"destroyModel.docx");
            if(!outputFile.exists()){
                outputFile.createNewFile();
                ClassPathResource classPathResource = new ClassPathResource("yijiaoModel/destroy.docx");
                InputStream inputStream = null;
                OutputStream outputStream1 = null;
                try {
                    inputStream = classPathResource.getInputStream();
                    // 创建输出文件的输出流
                    outputStream1 = new FileOutputStream(outputFile);
                    // 创建一个缓冲区，用于高效的数据传输
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    // 从输入流中读取数据，并写入到输出流中
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream1.write(buffer, 0, bytesRead);
                    }
                }catch (Exception e){
                    throw e;
                }finally {
                    // 刷新并关闭流
                    if(outputStream1 !=null){
                        outputStream1.flush();
                    }
                    if(inputStream !=null){
                        inputStream.close();
                    }
                    if(outputStream1 !=null){
                        outputStream1.close();
                    }
                }
            }
            //文件输出地址，指定到文件
            //String outPath = uplodPath+File.separator+"destroy"+File.separator+destroyId+".docx";

            /*File dest = new File(outputFile);
            if (!dest.getParentFile().exists())
            {
                dest.getParentFile().mkdirs();// 新建文件夹
            }*/
            XWPFTemplate render = XWPFTemplate.compile(outputFile).render(dataMap);
            String tempFile = uplodPath+File.separator+"destroy"+File.separator+destroyId+"_temp.docx";
            render.writeToFile(tempFile);


            // 读取模板文件
            templateInputStream = new FileInputStream(tempFile);
            document = new XWPFDocument(templateInputStream);

            // 获取模板中的表格
            XWPFTable table = document.getTables().get(0);

            // 假设你要填充的数据是一个列表
            //List<String[]> data = getData();

            // 遍历数据并添加到表格中
            for (String[] rowData : data) {
                XWPFTableRow newRow = table.createRow();
                for (int i = 0; i < rowData.length; i++) {
                    XWPFTableCell cell = newRow.getCell(i);
                    cell.setText(rowData[i]);
                }
            }

            // 保存生成的 Word 文件
            outputStream = new FileOutputStream(outPath);
            document.write(outputStream);
            return outPath;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }finally {
           try {
               // 关闭流
               if(outputStream !=null){
                   outputStream.close();
               }
               if(templateInputStream !=null){
                   templateInputStream.close();
               }
               if(document !=null){
                   document.close();
               }

           }catch (IOException ioException){
               logger.error(ioException.getMessage(),ioException);
           }
        }
        return null;
    }

    private String getName(String code){
        if(StringUtils.isNotEmpty(code)){
            if("1".equals(code)){
                return "续存";
            }else if("2".equals(code)){
                return "销毁";
            }
        }
        return "";
    }

    @Override
    public Destroy destroyById(Long destroyId) {
        return destroyMapper.findById(destroyId);
    }


    private void updateDaStat(Long destroyId,String state){
        DestroyCar select = new  DestroyCar();
        select.setDestroyId(destroyId);
        List<DestroyCar> list = destroyCarMapper.findAll(select);
        for(DestroyCar da:list){
            Long id = da.getDaId();
            //2.根据分表查询门类
            TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(da.getCategoryId(),new TenantCategory().getTableName());
            //处理项目层
            Map<String,String> column = new HashMap<>();
            column.put("STATE",state);
            if(category.getType() == 3) {
                /*List<String> xmId = tenantItemFolderMapper.selectItemIdByFolderId(String.valueOf(id),new TenantItemFolder().getTableName());
                if(xmId!=null && xmId.size()>0){
                    //修改项目
                    TenantYqItem item = new TenantYqItem();
                    item.setColNames(column);
                    item.setItemId(Long.valueOf(xmId.get(0)));
                    //添加过程信息
                    addBehavior(new Long[]{Long.valueOf(xmId.get(0))},state);
                    itemMapper.updateItem(item); //主表
                    item.setTableName(category.getItemTableName());
                    itemMapper.updateItemDisperse(item);  //分表
                }*/
            }
            if(category.getType() == 1 || category.getType() == 3){
                //修改卷
                Long folderId = da.getDaId();
                TenantYqFolder yqFolder = new TenantYqFolder();
                yqFolder.setColNames(column);
                yqFolder.setFolderId(folderId);
                //添加过程信息
                addBehavior(new Long[]{folderId},state);
                folderMapper.updateYqFolder(yqFolder);
                yqFolder.setTableName(category.getFolderTableName());
                folderMapper.updateYqFolderDisperse(yqFolder);

                //修改件
                Long [] folderIds = new Long[]{folderId};
                Long [] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds,category.getFileTableName(),new TenantYqdaFolder().getTableName());

                //添加过程信息
                addBehavior(daIds,state);
                for(Long daId:daIds){
                    TenantYqda yqda = new TenantYqda();
                    yqda.setColNames(column);
                    yqda.setDaId(daId);
                    yqdaMapper.updateYqda(yqda);
                    yqda.setTableName(category.getFileTableName());
                    yqdaMapper.updateYqdaDisperse(yqda);

                    //删除电子文件
                    destroyMapper.delDocFile(category.getEfileTableName(),daId);
                }
            } else if(category.getType() == 0){
                //处理组件
                Long daId = da.getDaId();
                TenantYqda yqda = new TenantYqda();
                yqda.setColNames(column);
                yqda.setDaId(daId);
                //添加过程信息
                addBehavior(new Long[]{daId},state);
                yqdaMapper.updateYqda(yqda);
                yqda.setTableName(category.getFileTableName());
                yqdaMapper.updateYqdaDisperse(yqda);

                //删除电子文件
                destroyMapper.delDocFile(category.getEfileTableName(),daId);
            }
        }
    }

    public void addBehavior(Long[] ids,String state){
        BusinessBehavior behavior = BusinessBehavior.XIAOHUI;
        if(null!=behavior){
            List<Long> daIds = Arrays.asList(ids);
            BusinessBehaviorUtil.add(daIds, behavior);
        }
    }

}
